package com.sihuatech.coreagent.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sihuatech.coreagent.send.RequestSender;

import javax.servlet.ServletException;

@Service
public class SendService {
	private static final Logger logger = LoggerFactory.getLogger(SendService.class);

	/**
	 * 发送xml到第三方
	 * @param request
	 * @return
	 */
	public String sendToThird(String request,String url,String header) {
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Content-Type", "multipart/form-data; boundary=" + header);
		headerMap.put("Connection", "close");
		RequestSender requestSender = RequestSender.getInstance();
		String reponseStr = requestSender.requestInvokerrViaPostMethod(url, request,
				"UTF-8", -1, -1, headerMap);
		return reponseStr;
	}

	public String execute(String xmlhead,String xmlbody,String url) throws ServletException, IOException {
		logger.info("xmlhead == \n" + xmlhead);
		logger.info("xmlbody == \n" + xmlbody);
		// 用远程服务的URL设置生成POST方法，供HTTP客户端执行
		String remoteUrl = url;
		PostMethod method = new PostMethod(remoteUrl);
		HttpClient HTTP_CLINET = new HttpClient();
		synchronized (HTTP_CLINET) {
			try {
				//使用多重发送方式,发送两个独立的两个XML Part,基于Content-Type="multipart/form-data"形式的表单
				Part[] parts = {new StringPart("xmlhead",xmlhead), new StringPart("xmlbody",xmlbody)}; //StringPart和FilePart都可以放进去
				RequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());
				method.setRequestEntity(requestEntity);
				method.setRequestHeader("Connection","close");
				method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
				//链接超时 30秒
				HTTP_CLINET.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
				//读取超时 30秒
				HTTP_CLINET.getHttpConnectionManager().getParams().setSoTimeout(30000);

				HTTP_CLINET.executeMethod(method);

				String[] result = new String[2];
				result[0] = String.valueOf(method.getStatusCode());
				result[1] = method.getResponseBodyAsString();
				logger.info("http status : " + result[0]);
			}
			catch (Exception e) {
				logger.error("错误的请求 == \n" + e);
			}
		}
		return method.getResponseBodyAsString();
	}
	
	/**
	 * 发送到下沉省份
	 * @param xmlString
	 * @return
	 */
	public String sendToSinkProvince(String xmlString,String url) {
		if (StringUtils.isNotEmpty(xmlString) && StringUtils.isNotEmpty(url)) {		    
				PostMethod post = null;
				String returnXml = null;			
				try {
					HttpClient httpclient = new HttpClient();
					post = new PostMethod(url);
					RequestEntity entity = new StringRequestEntity(xmlString, "text/xml", "UTF-8");
					post.setRequestEntity(entity);
					httpclient.executeMethod(post);
					if (post.getStatusCode() == HttpStatus.SC_OK) {
						returnXml = post.getResponseBodyAsString();
					}
					return returnXml;
				} catch (Exception e) {
					logger.error("XML post 失败!", e);
				} finally {
					if (null != post) {
						post.releaseConnection();
					}
				}
			}
		return null;
	}

	/**
	 * 网状网请求agent发往分省
	 * @param request
	 * @param url
	 * @param header
	 * @return
	 */
	public String sendToThird2(String request,String url,String header) {
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Content-Type", "text/plain; boundary=" + header);
		headerMap.put("Connection", "close");
		RequestSender requestSender = RequestSender.getInstance();
		String reponseStr = requestSender.requestInvokerrViaPostMethod(url, request,
				"UTF-8", -1, -1, headerMap);
		return reponseStr;
	}
	
}
